package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Description: 居民表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "居民表")
@RestController
@RequestMapping("/sggg/sgMember")
@Slf4j
public class SgMemberController extends JeecgController<SgMember, ISgMemberService> {

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISgSigningRecordService sgSigningRecordService; // 签约

    @Autowired
    private ISgTreatmentAssistService sgTreatmentAssistService; // 协诊

    @Autowired
    private ISgBlutdruckRecordService sgBlutdruckRecordService;

    @Autowired
    private ISgGlucoseRecordService sgGlucoseRecordService;

    @Autowired
    private ISgLipidRecordService sgLipidRecordService;

    @Autowired
    private ISgRemindRecordService sgRemindRecordService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISgTaskService taskService;

    @Autowired
    private ISgItemService itemService;

    @Autowired
    private ISgOperationRecordsService operationRecordsService;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISgSmsService sgSmsService;

    /**
     * 根据身份证获取性别
     *
     * @param idCard
     * @return
     */
    public static Integer getSexForIdCard(String idCard) {
        idCard = idCard.replaceAll(" ", "");
        idCard = idCard.replaceAll(" ", "");
        char genderCode = idCard.charAt(16);
        Integer gender = (genderCode % 2 == 0) ? 1 : 0;
        return gender;
    }

    /**
     * 根据身份证号码获取出生日期
     *
     * @param idCard 身份证号码
     * @return 出生日期字符串，格式为 yyyy-MM-dd
     */
    public static Date getBirthDate(String idCard) {
        String birthDate = null;
        try {
            idCard = idCard.replaceAll(" ", "");
            idCard = idCard.replaceAll(" ", "");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = sdf.parse(idCard.substring(6, 14));
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DAY_OF_MONTH);
            birthDate = String.format("%04d-%02d-%02d", year, month, day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return getDateTime(birthDate);
    }

    /**
     * String类型的时间转换为Date
     *
     * @param time
     * @return
     */
    public static Date getDateTime(String time) {
        String pattern = "yyyy-MM-dd"; // 时间字符串的格式
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 批量设置预警值
     *
     * @param json json
     * @return 结果
     */
    @PostMapping("/setAlert")
    public Result<String> setAlert(@RequestBody JSONObject json) {
        for (String id : json.getString("ids").split(",")) {
            SgMember m = json.toJavaObject(SgMember.class);
            m.setId(id);
            sgMemberService.updateById(m);
        }
        return Result.OK();
    }

    @ApiOperation(value = "居民表-分页列表查询", notes = "居民表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgMember>> queryPageList(SgMember sgMember,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<SgMember> page = new Page<>(pageNo, pageSize);

        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();
        if (sgMember.getType() != null) {
            queryWrapper.eq("type", sgMember.getType());
        }

        if (Strings.isNotBlank(sgMember.getName())) {
            queryWrapper.like("name", sgMember.getName());
        }

        if (sgMember.getSex() != null) {
            queryWrapper.eq("sex", sgMember.getSex());
        }

        if (Strings.isNotBlank(sgMember.getPhone())) {
            queryWrapper.like("phone", sgMember.getPhone());
        }

        if (Strings.isNotBlank(sgMember.getIdCard())) {
            queryWrapper.like("id_card", sgMember.getIdCard());
        }

        if (Strings.isNotBlank(sgMember.getThreeTag())) {
            queryWrapper.like("three_tag", sgMember.getThreeTag());
        }

        if (Strings.isNotBlank(sgMember.getRegion())) {
            queryWrapper.like("region", sgMember.getRegion().replaceAll(",", "/"));
        }

        queryWrapper.eq("del_flag", 0);

        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        // 选择了含下属没选择机构
        if (Strings.isNotBlank(sgMember.getIsDown()) && Strings.isBlank(sgMember.getSysOrgCode())) {
            queryWrapper.like("sys_org_code", sysUser.getOrgCode());
        } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isBlank(sgMember.getIsDown())) {
            // 选择了机构，没选择含下属
            if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
                queryWrapper.eq("sys_org_code", sgMember.getSysOrgCode());
            } else if (!roleCode.contains("admin")) {
                queryWrapper.eq("doctor_id", sysUser.getId());
            }
        } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isNotBlank(sgMember.getIsDown())) {
            // 即选择了机构，又选择了含下属
            queryWrapper.like("sys_org_code", sgMember.getSysOrgCode());
        } else {
            // 超级管理员可以查看全部、机构管理员（医生）只查看本机构下、(机构管理员)
            if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
                SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
                SysUser sysUser1 = sysUserService.getById(sysUser.getId());
                // 判断当前登录人的所属机构
                if (sysDepart != null) {
                    // 根据部门表DeptAttr（机构属性）判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
                    if (sysDepart.getDeptAttr() != null && sysDepart.getDeptAttr().length() != 0) {
                        // 1.三高之家 村级
                        if (sysDepart.getDeptAttr().equals("1")) {
                            // 村医：查询自己所在的村以及自己所负责的居民
                                queryWrapper.and(wrapper -> wrapper.eq("sys_org_code",
                                sysUser.getOrgCode()).or().eq("doctor_id", sysUser.getId().toString()));
                        }
                        // 2.三高基地 基地就是乡镇卫生院 不用根据负责的村室去查 直接查询本级以及下级机构的数据
                        else if (sysDepart.getDeptAttr().equals("2")) {
                            // 配置了所负责的村室
                            if(sysUser1.getResponsibleAgency()!=null){
                                String[] array = sysUser1.getResponsibleAgency().split(",");
                                List<String> responsibleAgencies = Arrays.asList(array);
                                queryWrapper.and(wrapper -> wrapper.in("sys_org_code", responsibleAgencies).
                                        or().eq("doctor_id", sysUser.getId().toString()));
                            }else{
                                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
                            }
                        }
                        // 3.三高中心
                        else if (sysDepart.getDeptAttr().equals("3")) {
                            // 配置了所负责的村室
                            if(sysUser1.getResponsibleAgency()!=null){
                                String[] array = sysUser1.getResponsibleAgency().split(",");
                                List<String> responsibleAgencies = Arrays.asList(array);
                                queryWrapper.and(wrapper -> wrapper.in("sys_org_code",
                                        responsibleAgencies).or().eq("doctor_id", sysUser.getId().toString()));
                            }else{
                                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
                            }
                        }
                    } else {
                        queryWrapper.eq("doctor_id", sysUser.getId().toString());
                    }
                } else {
                    // 当前登录的医生所属机构不是三高之家、三高基地、三高中心的，普通医生权限
                    if (sysUser1.getResponsibleAgency() != null) {
                        // 查询当前登录的医生所负责的村室的居民及当前登录的医生下的居民
                        String[] array = sysUser1.getResponsibleAgency().split(",");
                        List<String> responsibleAgencies = Arrays.asList(array);
                        queryWrapper.and(wrapper -> wrapper.in("sys_org_code", responsibleAgencies).or().eq("doctor_id", sysUser.getId().toString()));
                    } else {
                        // 查询当前登录的医生下的居民
                        queryWrapper.eq("doctor_id", sysUser.getId().toString());
                    }
                }
            }else{
                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
            }
        }

        if (sgMember.getStatus() != null) {
            queryWrapper.eq("status", sgMember.getStatus());
        }

        queryWrapper.select("id", "name", "nick_name", "sex", "phone", "id_card",
                "three_tag", "sys_org_code", "region", "smoking", "drinking", "source",
                "compliance", "address", "birthday", "height", "weight", "bmi", "waistline",
                "remark", "type", "send_drug", "manage_top", "urgent_name", "urgent_phone",
                "urgent_relation", "doctor_id", "avatar");
        queryWrapper.orderByDesc("create_time");
        IPage<SgMember> pageList = sgMemberService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * xl ---- 2022年11月18日 获取家人列表
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping("/queryFamilyList")
    public Result<List<SgMember>> queryFamilyList(String mid) {
        return Result.OK(sgMemberService.list(
                new QueryWrapper<SgMember>().eq("parent_id", mid)
                        .select("id", "name", "nick_name", "sex", "phone", "id_card", "birthday")
        ));
    }

    @AutoLog(value = "居民表-添加")
    @ApiOperation(value = "居民表-添加", notes = "居民表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgMember sgMember) {
        if (Strings.isNotBlank(sgMember.getPhone())) {
            long count = sgMemberService.count(new QueryWrapper<SgMember>().eq("phone", sgMember.getPhone()).eq("del_flag", 0));
            if (count > 0) {
                SgMember sgMember1 = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("phone", sgMember.getPhone()));
                SysDepart sysDepart = sysDepartController.getOne(new QueryWrapper<SysDepart>().eq("org_code", sgMember1.getSysOrgCode()));
                return Result.error("手机号已存在！", sysDepart.getDepartName());
            }
        }
        if (Strings.isNotBlank(sgMember.getIdCard())) {
            long count = sgMemberService.count(new QueryWrapper<SgMember>().eq("id_card", sgMember.getIdCard()).eq("del_flag", 0));
            if (count > 0) {
                return Result.error("身份证号已存在！");
            }
        }
        // 添加家人的情况
        if (Strings.isNotBlank(sgMember.getParentId())) {
            SgMember m = sgMemberService.getById(sgMember.getParentId());
            sgMember.setSysOrgCode(m.getSysOrgCode());
        }
        // 实名认证
        /*if (!toolUtils.certification(sgMember.getName(), sgMember.getIdCard())) {
            return Result.error("身份信息认证失败！");
        }*/
        sgMember.setStatus(1);
        // 如果有所属医生的话，就是再管状态
        if (Strings.isNotBlank(sgMember.getDoctorId())) {
            sgMember.setManageTop(0);
        }

        // 设置预警值
        sgMember.setSbpvalMin(90.0);
        sgMember.setSbpvalMax(140.0);

        sgMember.setDbpvalMin(60.0);
        sgMember.setDbpvalMax(90.0);

        sgMember.setBodyfatMin(6.0);
        sgMember.setBodyfatMax(14.0);

        sgMember.setSugarMin(1.1);
        sgMember.setSugarMax(6.1);

        sgMember.setBloodMin(0.0);
        sgMember.setBloodMax(5.18);

        sgMemberService.save(sgMember);

        /* try {
            // 同步数据到云雀
            com.alibaba.fastjson.JSONObject profile = yunQueController.queryProfileDetails(sgMember.getIdCard());
            if (profile.isEmpty()) {
                yunQueController.addProfile(sgMember);
            }
        } catch (Exception e) {
            log.error("同步数据到云雀时出现错误: {}", e.getMessage());
        } */

        return Result.OK("添加成功！");
    }

    @AutoLog(value = "居民表-编辑")
    @ApiOperation(value = "居民表-编辑", notes = "居民表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgMember sgMember) {
        if (Strings.isNotBlank(sgMember.getPhone())) {
            long count =
                    sgMemberService.count(new QueryWrapper<SgMember>().eq("phone",
                            sgMember.getPhone()).ne("id", sgMember.getId()));
            if (count > 0) {
                SysDepart sysDepart = sysDepartController.getOne(new QueryWrapper<SysDepart>().eq("org_code", sgMember.getSysOrgCode()));
                return Result.error("手机号已存在！", sysDepart.getDepartName());
            }
        }
        if (Strings.isNotBlank(sgMember.getIdCard())) {
            long count = sgMemberService.count(new QueryWrapper<SgMember>().eq("id_card", sgMember.getIdCard()).ne("id", sgMember.getId()));
            if (count > 0) {
                return Result.error("身份证号已存在！");
            }
        }
        sgMemberService.updateById(sgMember);

//        try {
//            // 同步数据到云雀
//            com.alibaba.fastjson.JSONObject profile = yunQueController.queryProfileDetails(sgMember.getIdCard());
//            if (profile.isEmpty()) {
//                yunQueController.addProfile(sgMember);
//            }
//        } catch (Exception e) {
//            log.error("同步数据到云雀时出现错误: {}", e.getMessage());
//        }

        // 删除此用户token，让他从新登录，获取最新信息
        redisUtil.removeAll(CommonConstant.PREFIX_MEMBER_TOKEN + sgMember.getId());
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "居民表-通过id删除")
    @ApiOperation(value = "居民表-通过id删除", notes = "居民表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        // 签约的服务项有没有到期
        SgSigningRecord signingRecord = sgSigningRecordService.getOne(
                new QueryWrapper<SgSigningRecord>()
                        .eq("member_id", id)
                        .orderByDesc("end_time")
                        .last("limit 1")
                        .select("id", "end_time")
        );
        if (signingRecord != null) {
            if (new Date().before(signingRecord.getEndTime())) {
                return Result.error("删除失败，该居民有服务未完成，请完成所有的服务后删除！");
            }
        }
        // 查询此用户是否在待转诊、待协诊、诊疗中
        long count = sgTreatmentAssistService.count(
                new QueryWrapper<SgTreatmentAssist>()
                        .eq("member_id", id)
                        .in("status", 0, 1, 2)
        );
        if (count >= 1) {
            return Result.error("删除失败，该居民有未完成的协诊，请完成后删除！");
        }

        sgMemberService.removeById(id);
        // 把这个用户的缓存清除掉，强制退出小程序
        redisUtil.removeAll(CommonConstant.PREFIX_MEMBER_TOKEN + id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "居民表-批量删除")
    @ApiOperation(value = "居民表-批量删除", notes = "居民表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        for (String id : ids.split(",")) {
            // 签约的服务项有没有到期
            SgSigningRecord signingRecord = sgSigningRecordService.getOne(
                    new QueryWrapper<SgSigningRecord>()
                            .eq("member_id", id)
                            .orderByDesc("end_time")
                            .last("limit 1")
                            .select("id", "end_time")
            );
            if (signingRecord != null) {
                if (new Date().before(signingRecord.getEndTime())) {
                    return Result.error("删除失败，所选居民中有服务未完成，请完成所有的服务后删除！");
                }
            }
            // 查询此用户是否在待转诊、待协诊、诊疗中
            long count = sgTreatmentAssistService.count(
                    new QueryWrapper<SgTreatmentAssist>()
                            .eq("member_id", id)
                            .in("status", 0, 1, 2)
            );
            if (count >= 1) {
                return Result.error("删除失败，所选居民中有未完成的协诊，请完成后删除！");
            }
        }
        this.sgMemberService.removeByIds(Arrays.asList(ids.split(",")));
        // 清空token，强制退出
        for (String id : ids.split(",")) {
            redisUtil.removeAll(CommonConstant.PREFIX_MEMBER_TOKEN + id);
        }
        return Result.OK("批量删除成功!");
    }

    @ApiOperation(value = "居民表-通过id查询", notes = "居民表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgMember> queryById(@RequestParam(name = "id") String id) {
        SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id", id));
        if (sgMember == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgMember);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgMember sgMember) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        } else {
            if (sgMember.getType() != null) {
                queryWrapper.eq("type", sgMember.getType());
            }

            if (Strings.isNotBlank(sgMember.getName())) {
                queryWrapper.like("name", sgMember.getName());
            }

            if (sgMember.getSex() != null) {
                queryWrapper.eq("sex", sgMember.getSex());
            }

            if (Strings.isNotBlank(sgMember.getPhone())) {
                queryWrapper.like("phone", sgMember.getPhone());
            }

            if (Strings.isNotBlank(sgMember.getIdCard())) {
                queryWrapper.like("id_card", sgMember.getIdCard());
            }

            if (Strings.isNotBlank(sgMember.getThreeTag())) {
                queryWrapper.like("three_tag", sgMember.getThreeTag());
            }

            if (Strings.isNotBlank(sgMember.getRegion())) {
                queryWrapper.like("region", sgMember.getRegion().replaceAll(",", "/"));
            }

            String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
            // 选择了含下属没选择机构
            if (Strings.isNotBlank(sgMember.getIsDown()) && Strings.isBlank(sgMember.getSysOrgCode())) {
                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
            } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isBlank(sgMember.getIsDown())) {
                // 选择了机构，没选择含下属
                if (roleCode.contains("dept_manage")) {
                    queryWrapper.eq("sys_org_code", sgMember.getSysOrgCode());
                } else if (!roleCode.contains("admin")) {
                    queryWrapper.eq("doctor_id", sysUser.getId().toString());
                }
            } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isNotBlank(sgMember.getIsDown())) {
                // 即选择了机构，又选择了含下属
                queryWrapper.like("sys_org_code", sgMember.getSysOrgCode());
            } else {
                //#region 超级管理员可以查看全部、机构管理员（医生）只查看本机构下、
                if (roleCode.contains("dept_manage")) {
                    queryWrapper.eq("sys_org_code", sysUser.getOrgCode());
                } else if (!roleCode.contains("admin")) {
                    queryWrapper.eq("doctor_id", sysUser.getId());
                }
                //#endregion
            }

            if (sgMember.getStatus() != null) {
                queryWrapper.eq("status", sgMember.getStatus());
            }
        }

        queryWrapper.select("*", "(select realname from sys_user where id = doctor_id) as doctorName,(select serial_number from sg_device_relevance where member_id = sg_member.id and type= 0 ORDER BY create_time LIMIT 1) as YModel,(select serial_number from sg_device_relevance where member_id = sg_member.id and type= 1 and is_delete =0 ORDER BY create_time LIMIT 1) as TModel,'血压计' as YDevice,'血糖仪' as TDevice");


        // Step.2 获取导出数据
        List<SgMember> exportList = sgMemberService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "居民信息");
        mv.addObject(NormalExcelConstants.CLASS, SgMember.class);
        // update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("居民信息" + "报表", "导出人:" + sysUser.getRealname(), "居民信息");
        exportParams.setImageBasePath(upLoadPath);
        // update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        // return super.importExcel(request, response, SgMember.class);
        return importExcel_(request, response, SgMember.class);
    }

    /**
     * 导入Excel模板
     *
     * @param request
     * @param response
     * @param clazz
     * @return
     */
    public Result<?> importExcel_(HttpServletRequest request, HttpServletResponse response, Class<SgMember> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            List<SgMember> list = new ArrayList<>();
            try {
                list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                JsonObject jsonObject = new JsonObject();
                for (int i = 0; i < list.size(); i++) {
                    Gson gson = new Gson();
                    String json = gson.toJson(list.get(i));
                    jsonObject = gson.fromJson(json, JsonObject.class);
                    list.get(i).setIdCard(jsonObject.get("idCard").toString().replaceAll(" ", "").replaceAll("\"", "").replaceAll(" ", ""));
                    list.get(i).setSex(getSexForIdCard(jsonObject.get("idCard").getAsString()));
                    list.get(i).setBirthday(getBirthDate(jsonObject.get("idCard").getAsString()));
                    list.get(i).setDoctorId(sysUser.getId());
                    list.get(i).setSource(3);
                }
                // update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                // region  添加测试数据循环
//                int i = 0;
//                for (SgMember item : list) {
//                    try {
//                        item.setIsTest(1);
//                        sgMemberService.save(item);
//                    } catch (Exception e) {
//                        log.info("已经重复{}", i + "条");
////                        log.info("重复数据",e.getMessage());
//                        i++;
//                    }
//                }
                // endregion


                service.saveBatch(list);
                // 400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                // 1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                // update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                // update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    int index = msg.indexOf("'"); // 找到第一个单引号的位置
                    if (index >= 0) {
                        String phone = msg.substring(index + 1, index + 12);
                        Optional<SgMember> result = list.stream()
                                .filter(item -> item.getPhone().equals(phone))
                                .findFirst(); // 找到第一条符合条件的实体数据
                        if (result.isPresent()) {
                            SgMember member = result.get();
                            return Result.error("文件导入失败:有重复数据！" + "姓名:" + member.getName() + ",手机号" + member.getPhone() + ",身份证号" + member.getIdCard());
                        }
                    } else {
                        return Result.error("文件导入失败:有重复数据！");
                    }
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                // update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcelValue", method = RequestMethod.POST)
    public Result<?> importExcelValue(HttpServletRequest request, HttpServletResponse response) {
        // return super.importExcel(request, response, SgMember.class);
        return importExcel__(request, response, SgMember.class);
    }

    /**
     * 导入Excel模板
     *
     * @param request
     * @param response
     * @param clazz
     * @return
     */
    public Result<?> importExcel__(HttpServletRequest request, HttpServletResponse response, Class<SgMember> clazz) {
        HttpServletRequest requests = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();

        byte[] bytes = Base64.getDecoder().decode(request.getHeader("keysList"));
        Map<String, String> map = new HashMap<>();
        String[] pairs = new String(bytes).split(",");
        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            String key = keyValue[0];
            String value = keyValue[1];
            map.put(key, value);
        }


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            List<SgMember> list = new ArrayList<>();
            try {
                list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);

                List<SgMember> list_item = new ArrayList<>();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    list_item = list.stream().filter(item -> item.getModeladdName().equals(entry.getKey()))
                            .map(items -> {
                                items.setDoctorId(entry.getValue());
                                return items;
                            }).collect(Collectors.toList());
                }

                AtomicReference<List<SgMember>> finalList = new AtomicReference<>(list);
                list_item.stream()
                        .filter(bMember -> finalList.get().stream().anyMatch(aMember -> aMember.getId() == bMember.getId()))
                        .findFirst()
                        .ifPresent(bMember -> {
                            finalList.set(finalList.get().stream()
                                    .map(aMember -> {
                                        if (aMember.getIdCard() == bMember.getIdCard()) {
                                            return bMember;
                                        } else {
                                            return aMember;
                                        }
                                    })
                                    .collect(Collectors.toList()));
                        });
                list = finalList.get();
                JsonObject jsonObject = new JsonObject();
                for (int i = 0; i < list.size(); i++) {
                    Gson gson = new Gson();
                    String json = gson.toJson(list.get(i));
                    jsonObject = gson.fromJson(json, JsonObject.class);
                    list.get(i).setIdCard(jsonObject.get("idCard").toString().replaceAll(" ", "").replaceAll("\"", "").replaceAll(" ", ""));
                    list.get(i).setSex(getSexForIdCard(jsonObject.get("idCard").getAsString()));
                    list.get(i).setBirthday(getBirthDate(jsonObject.get("idCard").getAsString()));
//                    list.get(i).setDoctorId(sysUser.getId());
                    list.get(i).setSource(3);
                }
                // update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                service.saveBatch(list);
                // 400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                // 1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                // update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                // update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    int index = msg.indexOf("'"); // 找到第一个单引号的位置
                    if (index >= 0) {
                        String phone = msg.substring(index + 1, index + 12);
                        Optional<SgMember> result = list.stream()
                                .filter(item -> item.getPhone().equals(phone))
                                .findFirst(); // 找到第一条符合条件的实体数据
                        if (result.isPresent()) {
                            SgMember member = result.get();
                            return Result.error("文件导入失败:有重复数据！" + "姓名:" + member.getName() + ",手机号" + member.getPhone() + ",身份证号" + member.getIdCard());
                        }
                    } else {
                        return Result.error("文件导入失败:有重复数据！");
                    }
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                // update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


    /**
     * 查询当前登录用户所在部门中未被删除掉的居民
     */
    @ApiOperation(value = "居民表-查询当前用户部门下居民", notes = "居民表-查询当前用户部门下居民")
    @GetMapping(value = "/queryList")
    public Result<List<SgMember>> queryList() {
        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();
        // 当前用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        List<SgMember> list = sgMemberService.list(queryWrapper.eq("doctor_id", loginUser.getId()).eq("del_flag", 0));

        return Result.OK(list);
    }

    /**
     * 查询当前在线居民
     */
    @ApiOperation(value = "居民表-查询当前在线居民", notes = "居民表-查询当前在线居民")
    @GetMapping(value = "/onlineList")
    public Result<Page<SgMember>> onlineList(SgMember sgMember,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();
        Page<SgMember> page = new Page<>(pageNo, pageSize);

        // 获取在线用户id
        List<String> memberIdList = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(CommonConstant.PREFIX_MEMBER_TOKEN.concat("*"));
        if (keys != null) {
            for (String key : keys) {
                memberIdList.add(key.substring(CommonConstant.PREFIX_MEMBER_TOKEN.length(), CommonConstant.PREFIX_MEMBER_TOKEN.length() + 19));
            }
        }

        Page<SgMember> sgMemberPage = null;
        if (memberIdList.size() > 0) {
            if (Strings.isNotBlank(sgMember.getName())) {
                queryWrapper.like("name", sgMember.getName());
            }
            sgMemberPage = sgMemberService.page(page, queryWrapper.in("id", memberIdList));
        }

        return Result.OK(sgMemberPage);

    }

    @ApiOperation(value = "居民表-在线居民强制退出", notes = "居民表-在线居民强制退出")
    @GetMapping(value = "/onlineLogOut")
    public Result<Object> onlineLogOut(SgMember sgMember) {
        Set<String> keys = redisTemplate.keys((CommonConstant.PREFIX_MEMBER_TOKEN + sgMember.getId()).concat("*"));

        if (ObjectUtil.isNull(keys)) {
            return Result.error("退出登录失败！");
        }

        redisUtil.removeAll(CommonConstant.PREFIX_MEMBER_TOKEN + sgMember.getId());
        return Result.ok("退出登录成功！");
    }

    /**
     * TODO     查询当前机构下居民
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/20 20:24
     * @Exception
     */
    @ApiOperation(value = "居民表-查询当前机构下居民", notes = "居民表-查询当前机构下居民")
    @GetMapping(value = "/queryByOrgCode")
    public Result<List<SgMember>> queryByOrgCode(@RequestParam(name = "orgCode") String orgCode) {

        List<SgMember> sgMember = sgMemberService.list(new QueryWrapper<SgMember>().eq("sys_org_code", orgCode));
        if (sgMember == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgMember);
    }

    /**
     * TODO     查询最近一周未测量的居民
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/20 20:24
     * @Exception
     */
    @ApiOperation(value = "居民表-查询最近一周未测量的居民", notes = "居民表-查询最近一周未测量的居民")
    @GetMapping(value = "/weekNotMeasured")
    public Result<IPage<SgMember>> weekNotMeasured(boolean Bindstatus, int type, String name, String phone,
                                                   @RequestParam(name = "day", defaultValue = "7") Integer day,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前挡路用户的角色编码
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        QueryWrapper<SgMember> queryWrap = new QueryWrapper<>();
        queryWrap.like("three_tag", type)
                .like(Strings.isNotBlank(name), "name", name).like(Strings.isNotBlank(phone), "phone", phone);

        if (roleCode.contains("dept_manage")) {
            // 机构管理员
            queryWrap.eq("sys_org_code", sysUser.getOrgCode());
        }
        // 超级管理员可以查看本级以及下级机构
        else if (roleCode.contains("admin")) {
            queryWrap.like("sys_org_code", sysUser.getOrgCode());
        } else if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
            // 医生，只查询自己所管辖的患者
            queryWrap.eq("doctor_id", sysUser.getId());
        }

//        List<SgMember> sgMembers = sgMemberService.list(queryWrap);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -day);
        Date Createtime = cal.getTime();
        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Createtime);
        Page<SgMember> page = new Page<>(pageNo, pageSize);
        IPage<SgMember> list = new Page<>();
        List<SgMember> list_item = new ArrayList<>();
        Page<SgMember> SgBlutdruckRecord_page = new Page<SgMember>(pageNo, pageSize);
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        List<String> responsibleAgencies = new ArrayList<>();
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setOrgCode(sysUser1.getOrgCode());
//                queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
//            queryWrapper.like("sys_org_code",sysUser.getOrgCode());
            sysUser.setOrgCode(sysUser1.getOrgCode());
        } else {
//            queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            sysUser.setOrgCode(sysUser1.getOrgCode());
        }
        int deviceType;
        // type 0高血压1高血糖2高血脂
        switch (type) {
            case 0: {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(formatStr);
                SgBlutdruckRecord sgBlutdruckRecord = new SgBlutdruckRecord();
                sgBlutdruckRecord.setSysOrgCode(sysUser.getOrgCode());
                sgBlutdruckRecord.setMeasuringTime(date);
                System.out.println("转换为String格式：" + date);
                deviceType = 0;
                IPage<SgMember> pageList = sgBlutdruckRecordService.queryPageListBySql(SgBlutdruckRecord_page, sgBlutdruckRecord.getSysOrgCode(), responsibleAgencies, day, roleCode, sysUser.getId(), name, phone, Bindstatus, deviceType);
                return Result.ok(pageList);
            }
            case 1: {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(formatStr);
                SgGlucoseRecord sgGlucoseRecord = new SgGlucoseRecord();
                sgGlucoseRecord.setSysOrgCode(sysUser.getOrgCode());
                sgGlucoseRecord.setMeasuringTime(date);
                System.out.println("转换为String格式：" + date);
                deviceType = 1;
                IPage<SgMember> pageList = sgGlucoseRecordService.queryPageListBySqlxt(SgBlutdruckRecord_page, sgGlucoseRecord.getSysOrgCode(), responsibleAgencies, day, roleCode, sysUser.getId(), name, phone, Bindstatus, deviceType);
                return Result.ok(pageList);
            }
            case 2: {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(formatStr);
                SgLipidRecord sgLipidRecord = new SgLipidRecord();
                sgLipidRecord.setSysOrgCode(sysUser.getOrgCode());
                sgLipidRecord.setMeasuringTime(date);
                System.out.println("转换为String格式：" + date);
                deviceType = 2;
                IPage<SgMember> pageList = sgLipidRecordService.queryPageListBySqlxz(SgBlutdruckRecord_page, sgLipidRecord.getSysOrgCode(), responsibleAgencies, day, roleCode, sysUser.getId(), name, phone, Bindstatus, deviceType);
                return Result.ok(pageList);
            }
        }
        return Result.error(null);
    }

    @ApiOperation(value = "最近一周未测量--提醒", notes = "最近一周未测量--提醒")
    @GetMapping(value = "/remindMember")
    public Result<String> remindMember(SgMember sgMember) {
        try {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            SgRemindRecord sgRemindRecord = new SgRemindRecord();
            sgRemindRecord.setMemberId(sgMember.getId());
            sgRemindRecord.setDoctorId(sysUser.getId());
            sgRemindRecord.setRemindTime(DateTime.now());
            sgRemindRecordService.save(sgRemindRecord);

            SgMember member = sgMemberService.getById(sgMember.getId());
            if (member.getPhone() != null) {
                JSONObject obj = new JSONObject();
                String remark = sgMember.getType().equals("0") ? "血压" : sgMember.getType().equals("1") ? "血糖" : "血压";
                SgSms sms = sgSmsService.getOne(new QueryWrapper<SgSms>().eq("sys_org_code", member.getSysOrgCode()).eq("sms_type", 2));
                if (sms != null) {
                    String[] params = sms.getTemplateParam().split(",");
                    for (String param : params) {
                        if (param.equals("name")) {
                            obj.put("name", member.getName());
                        } else if (param.equals("type")) {
                            obj.put("type", remark);
                        }
                    }
                    DySmsEnum.NOT_TESTED_A_WEEK_TEMPLATE_CODE.setTemplateCode(sms.getTemplateCode());
                    DySmsEnum.NOT_TESTED_A_WEEK_TEMPLATE_CODE.setSignName(sms.getSignName());
                    DySmsEnum.NOT_TESTED_A_WEEK_TEMPLATE_CODE.setKeys(sms.getTemplateParam());
                    JSONObject accessKey = new JSONObject();
                    accessKey.put("accessKeyId", sms.getAccessKey());
                    accessKey.put("accessKeySecret", sms.getSecretKey());
                    DySmsHelper.sendSms(member.getPhone(), obj, DySmsEnum.NOT_TESTED_A_WEEK_TEMPLATE_CODE, accessKey);
                }
            }
            return Result.ok("提醒成功!");
        } catch (Exception e) {
            return Result.error("提醒异常:原因{}", e.getMessage());
        }
    }

    /**
     * 根据居民id获取所属医生
     *
     * @param memberId
     * @return
     */
    @GetMapping("/getMemberDoctor")
    public Result<SysUser> getMemberDoctor(String memberId) {
        SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id", memberId));
        SysUser sysUser = new SysUser();
        if (sgMember.getDoctorId() != null) {
            sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sgMember.getDoctorId()));
        }
        return Result.ok(sysUser);
    }

    /**
     * TODO     根据居民id查询干预记录
     *
     * @return
     * @author WangJie
     * @date 2023/3/28 12:24
     * @Exception
     */
    @GetMapping("/interveneListByMid")
    public Result<List<Map<String, Object>>> interveneListByMid(String memberId, Integer type) {
        // type 0血压1血糖2血脂
        try {
            List<Map<String, Object>> data = sgMemberService.interveneListByMid(memberId, type);
            return Result.ok(data);
        } catch (Exception e) {
            return Result.error("根据居民id查询干预记录异常,原因{}" + e.getMessage());
        }
    }

    /**
     * 这是医生端请求申请，不用经过审核直接通过
     *
     * @param task 任务对象
     * @return 返回结果
     */
    @PostMapping("/updateCurrency")
    public Result<String> updateCurrency(@RequestBody SgTask task) {
        task.setStatus(1);
        task.setCreateTime(new Date());
        taskService.save(task);
        SgItem item = itemService.getById(task.getItemId());

        long count = 0L;
        QueryWrapper<SgTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_id", task.getItemId())
                .eq("member_id", task.getMemberId());

        if (item.getCycle() == 0) {// 每天刷新
            count = taskService.count(queryWrapper.last("and TO_DAYS(create_time) = TO_DAYS(NOW())"));
        } else if (item.getCycle() == 1) {// 每周刷新
            count = taskService.count(queryWrapper.last("and YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(NOW())"));
        } else if (item.getCycle() == 2) {// 每月刷新
            count = taskService.count(queryWrapper.last("and DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')"));
        } else if (item.getCycle() == 3) {// 每年刷新
            count = taskService.count(queryWrapper.last("and YEAR(create_time)=YEAR(NOW())"));
        } else if (item.getCycle() == 4) {// 每人仅限一次
            count = taskService.count(queryWrapper);
        } else if (item.getCycle() == 5) {// 每次刷新
            count = item.getPeriod();
        }

        if (item.getName().equals("附加任务")) {
            item.setCurrency(task.getCurrency());
        }

        if (item.getPeriod() == count) {
            // 添加获取积分记录
            SgOperationRecords records = new SgOperationRecords();
            records.setType(0);
            records.setMemberId(task.getMemberId());
            records.setTaskId(item.getId());
            records.setNumber(item.getCurrency());
            operationRecordsService.save(records);
            // 修改分数
            sgMemberService.updateCurrencyById(task.getMemberId(), item.getCurrency());
        }

        return Result.ok();
    }

    /**
     * 居民端提交审核审核
     *
     * @param task 任务对象
     * @return 返回结果
     */
    @PostMapping("/verifyCurrency")
    public Result<String> verifyCurrency(@RequestBody SgTask task) {
        task.setStatus(0);
        task.setCreateTime(new Date());
        taskService.save(task);
        return Result.ok();
    }

    /**
     * 居民健康币排行
     *
     * @return
     */
    @GetMapping("/memberCurrencyRanking")
    public Result<IPage<SgMember>> memberCurrencyRanking(SgMember sgMember,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgMember> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取角色信息
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgMember.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgMember.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        IPage<SgMember> pageList = sgMemberService.memberCurrencyRanking(page, sgMember, roleCode, sysUser.getOrgCode(), sysUser.getId());
        return Result.ok(pageList);
    }

    /**
     * 小程序健康币排行
     *
     * @param memberId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/appletsCurrencyRanking")
    public Result<IPage<SgMember>> appletsCurrencyRanking(String memberId,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        SgMember member = sgMemberService.getById(memberId);
        Page<SgMember> page = new Page<>(pageNo, pageSize);
        IPage<SgMember> membersList = sgMemberService.page(page, new QueryWrapper<SgMember>().eq("sys_org_code", member.getSysOrgCode()).orderByDesc("currency"));
        return Result.ok(membersList);
    }

    /**
     * 小程序健康币排行--获取前三名
     *
     * @param memberId
     * @return
     */
    @GetMapping("/topThree")
    public Result<Map<String, Object>> topThree(String memberId) {
        Map<String, Object> list = new HashMap<>();
        SgMember member = sgMemberService.getById(memberId);
        List<SgMember> members = sgMemberService.list(new QueryWrapper<SgMember>().eq("sys_org_code", member.getSysOrgCode()).orderByDesc("currency"));
        List<SgMember> TopThree = new ArrayList<>();
        TopThree.add(members.get(0));
        TopThree.add(members.get(1));
        TopThree.add(members.get(2));
        list.put("TopThree", TopThree);
        int i = 0;
        for (SgMember item : members) {
            i++;
            if (item.getId().equals(memberId)) {
                break;
            }
        }
        list.put("ranking", i);
        return Result.OK(list);
    }

    // region 根据Excel批量修改库里居民的依从性，抽烟，喝酒情况

    /**
     * 根据Excel批量修改库里居民的依从性，抽烟，喝酒情况
     */
    @RequestMapping(value = "/importExcelUpdate", method = RequestMethod.POST)
    public Result<?> importExcelUpdate(HttpServletRequest request, HttpServletResponse response) {
        return importExcelBatchUpdate(request, response, SgMember.class);
    }

    public Result<?> importExcelBatchUpdate(HttpServletRequest request, HttpServletResponse response, Class<SgMember> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            List<SgMember> list = new ArrayList<>();
            try {
                list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                JsonObject jsonObject = new JsonObject();
                for (int i = 0; i < list.size(); i++) {
                    Gson gson = new Gson();
                    String json = gson.toJson(list.get(i));
                    jsonObject = gson.fromJson(json, JsonObject.class);
                    list.get(i).setIdCard(jsonObject.get("idCard").toString().replaceAll(" ", "").replaceAll("\"", "").replaceAll(" ", ""));
                    list.get(i).setSex(getSexForIdCard(jsonObject.get("idCard").getAsString()));
                    list.get(i).setBirthday(getBirthDate(jsonObject.get("idCard").getAsString()));
                    list.get(i).setDoctorId(sysUser.getId());
                    list.get(i).setSource(3);
                }
                long start = System.currentTimeMillis();

                for (SgMember item : list) {
                    try {
                        SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id_card", item.getIdCard()));
                        if (sgMember != null) {
                            sgMember.setIdCard(item.getIdCard());
                            sgMember.setCompliance(item.getCompliance());
                            sgMember.setSmoking(item.getSmoking());
                            sgMember.setDrinking(item.getDrinking());
                            sgMemberService.save(item);
                        }
                    } catch (Exception e) {
                        log.info("修改异常{}", e.getMessage());
                    }
                }
                return Result.ok("数据批量修改成功！数据行数：" + list.size());
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
    // endregion
}
